{% extends 'oracle/base.html' %}
{% load static %}
{% load oracle %}

{% block css %}
    <link href="{% static 'oracle/css/plugins/icheck/skins/flat/red.css' %}" rel="stylesheet">
{% endblock %}

{% block content %}
    <div class="wrapper wrapper-content animated fadeInRight">
        <div class="row">
            <div class="col-lg-12">
                <div class="ibox" id="register_box">
                    <div class="ibox-title">
                        <h5>
                            待关联权限列表
                            <small class="m-l-sm">单条加入未关联菜单的权限！</small>
                        </h5>
                        <div class="ibox-tools">
                            <a class="btn btn-primary btn-rounded btn-sm" href="#" id="menu_link_add_form_submit">
                                <i class="fa fa-puzzle-piece"></i> 提交权限关联表单
                            </a>
                            {% if request|has_permission:'oracle:multi_permission_add' %}
                                <a class="btn btn-success btn-rounded btn-sm" style="color: white!important;"
                                   href="{% url 'oracle:multi_permission_add' %}">
                                    <i class="fa fa-superpowers"></i> 权限批量操作
                                </a>
                            {% endif %}
                            {% if request|has_permission:'oracle:menu_list' %}
                                <a class="btn btn-info btn-rounded btn-sm" style="color: white!important;"
                                   href="{% url 'oracle:menu_list' %}">
                                    <i class="fa fa-bolt"></i> 返回菜单列表
                                </a>
                            {% endif %}
                            <a class="btn btn-info btn-circle collapse-link" type="button"
                               style="color: white!important;">
                                <i class="fa fa-chevron-up"></i>
                            </a>
                        </div>
                    </div>
                    <div class="ibox-content">
                        <form method="post" action="" id="menu_link_add_form">
                            {% csrf_token %}
                            {{ data.menu_add_formset.management_form }}
                            <table class="table">
                                <thead>
                                <tr>
                                    <th scope="col">
                                        <div>
                                            <input type="checkbox" id="select_all_checkbox">
                                        </div>
                                    </th>
                                    <th scope="col">#</th>
                                    <th scope="col">标题</th>
                                    <th scope="col">ICON</th>
                                    <th scope="col">权限</th>
                                    <th scope="col">父级菜单</th>
                                    <th scope="col">关联菜单</th>
                                    <th scope="col" class="d-none">状态</th>
                                    <th scope="col" class="d-none">等级</th>
                                </tr>
                                </thead>
                                <tbody>
                                {% for form in data.menu_add_formset %}
                                    <tr>
                                        <td>
                                            <input type="checkbox" id="register_{{ forloop.counter }}" class="d-block">
                                        </td>
                                        <td>{{ forloop.counter }}</td>
                                        {% for field in form %}
                                            <td
                                                    {% if field.name == "key" or field.name == "status" or field.name == "level" %}
                                                        class="d-none"
                                                    {% endif %}
                                            >
                                                {{ field }}
                                                <span style="color: red">{{ field.errors.0 }}</span></td>
                                        {% endfor %}
                                    </tr>
                                {% endfor %}
                                </tbody>
                            </table>
                        </form>
                    </div>
                </div>
            </div>

            <div class="col-lg-12">
                <div class="ibox ">
                    <div class="ibox-title">
                        <h5>
                            全部菜单列表
                            <small class="m-l-sm">修改已存在的关联菜单信息！</small>
                        </h5>
                        <div class="ibox-tools">
                            <a class="btn btn-primary btn-rounded btn-sm" href="#" id="menu_link_edit_form_submit">
                                <i class="fa fa-puzzle-piece"></i> 更新权限关联表单
                            </a>
                            <a class="btn btn-info btn-circle collapse-link" type="button"
                               style="color: white!important;">
                                <i class="fa fa-chevron-up"></i>
                            </a>
                        </div>
                    </div>
                    <div class="ibox-content">
                        <form method="post" action="" id="menu_link_edit_form">
                            {% csrf_token %}
                            {{ data.menu_edit_formset.management_form }}
                            <table class="table">
                                <thead>
                                <tr>
                                    <th scope="col">#</th>
                                    <th scope="col" class="d-none">key</th>
                                    <th scope="col">标题</th>
                                    <th scope="col">ICON</th>
                                    <th scope="col">权限</th>
                                    <th scope="col">父级菜单</th>
                                    <th scope="col">关联菜单</th>
                                    <th scope="col" class="d-none">状态</th>
                                    <th scope="col" class="d-none">等级</th>
                                </tr>
                                </thead>
                                <tbody>
                                {% for form in data.menu_edit_formset %}
                                    <tr>
                                        <td>{{ forloop.counter }}</td>
                                        {% for field in form %}
                                            <td
                                                    {% if field.name == 'key' or field.name == 'status' or field.name == 'level' %}
                                                        class="d-none"
                                                    {% endif %}
                                            >
                                                {{ field }}
                                                <span style="color: red">{{ field.errors.0 }}</span>
                                            </td>
                                        {% endfor %}
                                    </tr>
                                {% endfor %}
                                </tbody>
                            </table>
                        </form>
                    </div>
                </div>
            </div>
        </div>
    </div>
{% endblock %}

{% block js %}
    <!-- iCheck -->
    <script src="{% static 'oracle/js/plugins/icheck/icheck.min.js' %}"></script>
    <script src="{% static 'oracle/js/plugins/sweetalert/sweetalert.min.js' %}"></script>
    <script>
        // 通过icheck回调事件完成全选功能
        $('#select_all_checkbox').on("ifChecked", function (event) {
            $('#register_box input[type=checkbox]').iCheck('check');
        }).on("ifUnchecked", function (event) {
            $('#register_box input[type=checkbox]').iCheck('uncheck');
        })

        // checkbox样式
        $('#register_box input').iCheck({
            checkboxClass: 'icheckbox_flat-red',
            radioClass: 'iradio_flat-red',
        });

        $("#menu_link_add_form_submit").click(function (event) {
            let data = {
                // 获取csrf type类型 以及formset信息
                "csrfmiddlewaretoken": $("#menu_link_add_form input[name='csrfmiddlewaretoken']").val(),
                "form-TOTAL_FORMS": $("#menu_link_add_form #id_form-TOTAL_FORMS").val(),
                "form-INITIAL_FORMS": $("#menu_link_add_form #id_form-INITIAL_FORMS").val(),
                "form-MIN_NUM_FORMS": $("#menu_link_add_form #id_form-MIN_NUM_FORMS").val(),
                "form-MAX_NUM_FORMS": $("#menu_link_add_form #id_form-MAX_NUM_FORMS").val(),
                "type": "add",
            }

            // 新key与旧key的对应关系，为以后出现错误在对应输入框显示准备
            let relation = {};
            let tdinput, name;
            // 定义有多少合法的form项
            let count = 0;
            // 定义临时字典
            let td_dict = {};

            // 循环table 每一行是一个form
            $("#menu_link_add_form table tr:gt(0)").each(function (tr_index) {
                // 循环每一行的每一个输入框
                if ($(this).children("td:eq(0)").children().children("input").is(":checked")) {
                    // 不是第二个输入框进行处理，第二个输入框是生成的列表顺序，忽略不计
                    $(this).children("td:gt(1)").each(function (td_index) {
                        // 获取输入值
                        tdinput = $(this).children()
                        // 获取name属性
                        name = tdinput.attr("name")
                        // 输入框数值
                        value = tdinput.val().trim()
                        // 没有退出则把当前的信息进行保存
                        td_dict[name] = value
                    });
                    // 如果有td_dict 说明需要保存这个form
                    if (Object.keys(td_dict).length !== 0) {
                        for (name in td_dict) {
                            // 保存内容到data里面并修改name
                            data[name.replace(/\d+/, count)] = td_dict[name];
                            // 记录关联关系
                            relation[count] = name.substring(0, name.lastIndexOf("-"))
                        }
                        // 记录几个form需要提交
                        count += 1
                    }
                }
            });
            // 没有有效数据，直接返回信息，不请求接口
            if (count === 0) {
                swal({
                    title: "没有数据！",
                    text: "没有检测到要提交的数据，请选择提交的数据后再进行提交",
                    icon: "info",
                    button: " 确 定 ",
                });
                return false;
            }
            // 需要提交 form 数量
            data["form-TOTAL_FORMS"] = count.toString()
            data["form-INITIAL_FORMS"] = count.toString()
            let url = window.location.href;
            $.ajax({
                url: url,
                type: "POST",
                data: data,
                success: function (data) {
                    if (data["status"] === 0) {
                        // 成功刷新页面。可以手动更新页面，麻烦收益不高
                        window.location.reload();
                    } else {
                        // 数据有误，遍历数据错误 i 为目前遍历的第几个form
                        for (let i = 0; i < data["data"]["form"]["length"]; i++) {
                            let errors = data["data"]["form"][i]
                            for (let key in errors) {
                                // 对应位置显示错误信息
                                $("#menu_link_add_form table #id_" + relation[i] + "-" + key).next("span").text(errors[key][0])
                            }
                        }
                    }
                },
                error: function (data) {
                    console.log(data);
                }
            });
        })

        $("#menu_link_edit_form_submit").click(function (event) {
            let data = {
                // 获取csrf type类型 以及formset信息
                "csrfmiddlewaretoken": $("#menu_link_edit_form input[name='csrfmiddlewaretoken']").val(),
                "form-TOTAL_FORMS": $("#menu_link_edit_form #id_form-TOTAL_FORMS").val(),
                "form-INITIAL_FORMS": $("#menu_link_edit_form #id_form-INITIAL_FORMS").val(),
                "form-MIN_NUM_FORMS": $("#menu_link_edit_form #id_form-MIN_NUM_FORMS").val(),
                "form-MAX_NUM_FORMS": $("#menu_link_edit_form #id_form-MAX_NUM_FORMS").val(),
                "type": "update",
            }

            // 新key与旧key的对应关系，为以后出现错误在对应输入框显示准备
            let relation = {};
            let tdinput, name;
            // 定义有多少合法的form项
            let count = 0;
            // 定义临时字典
            let td_dict = {};

            // 循环table 每一行是一个form
            $("#menu_link_edit_form table tr:gt(0)").each(function (tr_index) {
                // 循环每一行的每一个输入框
                // 不是第一个输入框进行处理，第一个输入框是生成的列表顺序，忽略不计
                $(this).children("td:gt(0)").each(function (td_index) {
                    // 获取输入值
                    tdinput = $(this).children()
                    // 获取name属性
                    name = tdinput.attr("name")
                    // 输入框数值
                    value = tdinput.val().trim()
                    // 没有退出则把当前的信息进行保存
                    td_dict[name] = value
                });
                // 如果有td_dict 说明需要保存这个form
                if (Object.keys(td_dict).length !== 0) {
                    $.extend(data, td_dict)
                }
            });
            // 没有有效数据，直接返回信息，不请求接口
            if (Object.keys(td_dict).length <= 6) {
                swal({
                    title: "没有数据！",
                    text: "没有检测到要提交的数据，请选择提交的数据后再进行提交",
                    icon: "info",
                    button: " 确 定 ",
                });
                return false;
            }
            let url = window.location.href;
            $.ajax({
                url: url,
                type: "POST",
                data: data,
                success: function (data) {
                    if (data["status"] === 0) {
                        // 成功刷新页面。可以手动更新页面，麻烦收益不高
                        window.location.reload();
                    } else {
                        // 数据有误，遍历数据错误 i 为目前遍历的第几个form
                        for (let i = 0; i < data["data"]["form"]["length"]; i++) {
                            let errors = data["data"]["form"][i]
                            for (let key in errors) {
                                // 对应位置显示错误信息
                                $("#menu_link_edit_form table #id_form-" + i + "-" + key).next("span").text(errors[key][0])
                            }
                        }
                    }
                },
                error: function (data) {
                    console.log(data);
                }
            });
        })


    </script>
{% endblock %}
